import React, {useEffect, useMemo, useState, useCallback} from "react";
import {getUser, productImg, productWhiteImg } from "tiklab-core-ui";
import {useHistory} from "react-router";
import {productTitle} from "tiklab-core-ui/es/utils/product";
import "./LeftMenuCommonStyle.scss";
import {CaretLeftOutlined, CaretRightOutlined, QuestionCircleOutlined, SettingOutlined} from "@ant-design/icons";
import MessageDrawer from "../../setting/message/MessageDrawer";
import {Dropdown, Tooltip} from "antd";
import IconCommon from "../IconCommon";
import {Profile} from 'tiklab-licence-ui/es/commons';
import {AvatarLink as LicenceAvatarLink} from "tiklab-licence-ui";
import {useTheme} from "../hooks/useTheme";
import {useMenuExpanded} from "../hooks/useMenuExpanded";
import ExtensionCommon from "../ExtensionCommon/ExtensionCommon";

const LeftMenuCommon = (props) =>{
    const {
        menuData,          // 菜单项数组
        diffHeader,        // 菜单头部自定义内容区
        isFirst,           // 是否为首次加载（用于控制logo显示等）
        workspaceId,       // 当前工作区ID
        settingRouter,     // 设置页路由
        HelpLink,          // 帮助链接组件
        AppLink,           // 应用导航链接组件
        AvatarLink,        // 用户头像及相关链接组件 (可能是 LicenceAvatarLink)
        customLogo,        // 自定义Logo对象
        versionInfo        // 从 LeftNav 传入的版本信息 { expired: boolean, release: number }
    } = props;

    const history = useHistory();
    const LEFT_MENU_SELECT = localStorage.getItem("LEFT_MENU_SELECT");
    const [isExpanded, setIsExpanded] = useMenuExpanded();
    const [themeColor, setThemeColor] = useTheme();
    const [moreMenu, setMoreMenu] = useState([]);
    const [visibleMenuItems, setVisibleMenuItems] = useState([]);
    const [moreDropdownVisible, setMoreDropdownVisible] = useState(false);
    const THEME_DEFAULT = "theme-default";

    const resizeUpdate = useCallback(() => {
        const documentHeight = window.innerHeight;
        const menuHeight = documentHeight - 220;
        const menuNum = Math.floor(menuHeight / 65);

        if (menuData && menuData.length > menuNum && menuNum > 0) {
            // 如果菜单项过多，一部分放入更多
            setVisibleMenuItems(menuData.slice(0, menuNum - 1));
            setMoreMenu(menuData.slice(menuNum - 1));
        } else {
            // 否则全部显示
            setVisibleMenuItems(menuData || []);
            setMoreMenu([]);
        }
    }, [menuData]);

    useEffect(() => {
        // 监听窗口大小变化，动态调整可见菜单项
        window.addEventListener("resize", resizeUpdate);
        resizeUpdate();
        return () => {
            window.removeEventListener('resize', resizeUpdate);
        };
    }, [resizeUpdate]);

    /**
     * 页面跳转逻辑
     * @param {object} item - 被点击的菜单项对象 { router: string, key: string }
     */
    const clickToPage = (item) => {
        // 特殊处理概览页，虽然通常 item.router 已经是目标路径
        if(item.key==="overview"){
            history.push(`/workspace/overview`);
        } else {
            history.push(item.router);
        }
        localStorage.setItem("LEFT_MENU_SELECT",item.router);
    };

    // 菜单项内容的渲染组件
    const MenuItemContent = ({ item, isSelected }) => (
        <div
            className={`menu-box-nav-item-${themeColor}
                ${isSelected ? `select-link-${themeColor}` : ""}
                ${isExpanded ? "menu-box-nav-item-isExpanded" : "menu-box-nav-item-not-isExpanded"}
            `}
        >
            <div className={"menu-box-nav-item-detail"}>
                <svg className="icon" aria-hidden="true">
                    <use xlinkHref={`#icon-${item.icon}`}/>
                </svg>
            </div>
            <div className={`menu-box-nav-item-detail ${isExpanded ? "" : "menu-box-nav-item-title"}`}>
                {item.name}
            </div>
        </div>
    );

    /**
     * 渲染可见的菜单项列表
     * @param {Array} data - 菜单项数据列表 (通常是 visibleMenuItems)
     */
    const showMenuItem = (data) => {
        return data && data.map(item => {
            const isSelected = LEFT_MENU_SELECT === item.router; // 判断当前项是否被选中

            // 判断是否为扩展项且版本已过期
            if (item.extension && versionInfo && versionInfo.expired) {
                return (
                    <li key={item.key} className="menu-box-nav-item">
                        <ExtensionCommon
                            history={history}
                            id={item.router}
                            name={item.name}
                            // ViewContent 是一个函数，接收 ExtensionCommon 内部的 showModal 方法
                            ViewContent={({ showModal }) => (
                                // 这个 div 作为可点击区域，点击时调用 showModal 来显示 ExtensionCommon 的弹窗
                                <div onClick={showModal} style={{
                                    width: '100%',
                                    height: '100%',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                }}>
                                    <MenuItemContent item={item} isSelected={isSelected} />
                                </div>
                            )}
                        />
                    </li>
                );
            } else {
                return (
                    <li
                        key={item.key}
                        className="menu-box-nav-item"
                        onClick={() => clickToPage(item)} // 点击直接跳转
                    >
                        <MenuItemContent item={item} isSelected={isSelected} />
                    </li>
                );
            }
        });
    };

    // 更多下拉菜单的内容
    const showMore = (
        <div className={"more-menu-box"} style={{left: `${isExpanded ? "200px" : "75px"}`}}>
            {
                moreMenu.map(item => {
                    const isSelected = LEFT_MENU_SELECT === item.router;
                    // 更多中的项也应用相同的逻辑
                    const handleMoreItemClick = () => {
                        setMoreDropdownVisible(false);
                        clickToPage(item);
                    };

                    if (item.extension && versionInfo && versionInfo.expired) {
                        return (
                            <ExtensionCommon
                                key={item.key}
                                history={history}
                                id={item.router}
                                name={item.name}
                                ViewContent={({ showModal }) => (
                                    <div
                                        className={`more-menu-box-item ${isSelected ? "more-menu-box-item-action" : ""}`}
                                        onClick={() => {
                                            setMoreDropdownVisible(false);
                                            showModal();
                                        }}
                                    >
                                        <div>
                                            <svg className="icon" aria-hidden="true">
                                                <use xlinkHref={`#icon-${item.icon}`}/>
                                            </svg>
                                        </div>
                                        <div>{item.name}</div>
                                    </div>
                                )}
                            />
                        );
                    } else {
                        return (
                            <div
                                key={item.key}
                                className={`more-menu-box-item ${isSelected ? "more-menu-box-item-action" : ""}`}
                                onClick={handleMoreItemClick}
                            >
                                <div>
                                    <svg className="icon" aria-hidden="true">
                                        <use xlinkHref={`#icon-${item.icon}`}/>
                                    </svg>
                                </div>
                                <div>{item.name}</div>
                            </div>
                        );
                    }
                })
            }
        </div>
    );

    const moreItem = () => (
        <li
            key={"more"}
            className={`menu-box-nav-item `}
        >
            <Dropdown
                overlay={showMore} // 直接传递 overlay 内容
                trigger={['click']}
                open={moreDropdownVisible}
                onOpenChange={(visibleFlag) => setMoreDropdownVisible(visibleFlag)} // 控制下拉显隐
                placement="top"
            >
                <div
                    className={`menu-box-nav-item-${themeColor} ${isExpanded?"menu-box-nav-item-isExpanded":"menu-box-nav-item-not-isExpanded"}`}>
                    <div className={"menu-box-nav-item-detail"}>
                        <svg className="icon" aria-hidden="true">
                            <use xlinkHref= {`#icon-${themeColor===THEME_DEFAULT?"gengduo":"gengduo1"}`}/>
                        </svg>
                    </div>
                    {
                        isExpanded && <div className={"menu-box-nav-item-detail"}>更多</div>
                    }
                </div>
            </Dropdown>
        </li>
    );

    // 切换主题颜色
    const changeTheme = (type) =>{
        const themeMap = {
            black: "theme-black",
            blue: "theme-blue",
            default: "theme-default"
        };
        const theme = themeMap[type] || themeMap.default;
        setThemeColor(theme);
    };

    // 判断是否为 Electron Windows 环境
    const isElectronWindows = () => {
        const userAgent = navigator.userAgent.toLowerCase();
        const isElectron = userAgent.includes('electron');
        const isWindows = userAgent.includes('windows');
        return isElectron && isWindows;
    };

    // 显示Logo区域
    const showLogo = (currentCustomLogo, currentProductImg, currentProductWhiteImg, currentProductTitle, currentIsExpanded, currentThemeColor)=>{
        let dataImage;
        let title;
        if(currentCustomLogo){
            dataImage = currentCustomLogo?.image;
            title = currentCustomLogo?.name;
        } else {
            let useImg = currentThemeColor === THEME_DEFAULT ? currentProductImg : currentProductWhiteImg;
            dataImage = useImg;
            title = currentProductTitle;
        }

        return (
            <div style={{width: `${currentIsExpanded ? "200px" : ""}`}} className={'product-logo-box'} // 修正展开时宽度
                 onClick={() => clickToPage({router: "/index", key: "index" })}> {/* 点击Logo跳转到首页 */}
                <img src={dataImage} alt='logo'
                     className={`${currentIsExpanded ? "product-logo-expanded" : "product-logo"}`}/>
                {
                    currentIsExpanded && <div className={"productName"}>{title}</div>
                }
            </div>
        );
    };

    // 决定最终使用的 AvatarLink 组件
    const FinalAvatarLink = AvatarLink || LicenceAvatarLink;

    return (
        <div className={`menu-box ${isExpanded ? "menu-box-expended" : "menu-box-not-expended"} ${themeColor}`}>
            {/* Logo区域，根据条件显示 */}
            {
                isFirst && !isElectronWindows() && showLogo(customLogo, productImg.postin, productWhiteImg?.postin, productTitle.postin, isExpanded, themeColor)
            }
            <div className={"menu-box-flex"} style={{height:`${isFirst && !isElectronWindows() ? "calc(100% - 63px)" : "100%"}`}}> {/* 主菜单区域，高度动态计算 */}
                <ul className={"menu-box-nav"}> {/* 导航项列表 */}
                    {
                        diffHeader && diffHeader(isExpanded,themeColor,isElectronWindows) // 渲染菜单顶部的特定内容
                    }
                    {
                        showMenuItem(visibleMenuItems) // 渲染可见的菜单项
                    }
                    {
                        moreMenu && moreMenu.length > 0 && moreItem() // 如果有“更多”项，则渲染“更多”按钮
                    }
                </ul>

                <div className={"menu-box-bottom"}> {/* 菜单底部固定项区域 */}
                    {settingRouter && ( // 设置按钮
                        isExpanded
                            ? <div className={`menu-box-bottom-item-${themeColor} menu-box-bottom-item menu-box-bottom-item-isExpanded`} onClick={()=>clickToPage({router:settingRouter, key: "setting"})}>
                                <SettingOutlined style={{fontSize:"18px"}}/>
                                <div>设置</div>
                            </div>
                            : <Tooltip placement="right" title={"设置"}>
                                <div className={`menu-box-bottom-item-${themeColor} menu-box-bottom-item menu-box-bottom-item-not-isExpanded`}
                                     onClick={()=>clickToPage({router:settingRouter, key: "setting"})}
                                >
                                    <SettingOutlined style={{fontSize:"18px"}}/>
                                </div>
                            </Tooltip>
                    )}
                    {/* 消息抽屉 */}
                    {
                        isFirst && <MessageDrawer isExpanded={isExpanded} themeColor={themeColor}/>
                    }
                    {/* 帮助链接 */}
                    {
                        HelpLink && <HelpLink
                            bgroup={'postin'}
                            iconComponent= {
                                isExpanded
                                    ?<div className={`menu-box-bottom-item-${themeColor} menu-box-bottom-item menu-box-bottom-item-isExpanded`}>
                                        <QuestionCircleOutlined style={{fontSize:"18px"}}/>
                                        <div>帮助</div>
                                    </div>
                                    : <Tooltip placement="right" title={"帮助"}>
                                        <div className={`menu-box-bottom-item-${themeColor} menu-box-bottom-item menu-box-bottom-item-not-isExpanded`}>
                                            <QuestionCircleOutlined style={{fontSize:"18px"}}/>
                                        </div>
                                    </Tooltip>
                            }
                        />
                    }
                    {/* 应用导航链接 */}
                    {
                        AppLink && <AppLink
                            bgroup={'postin'}
                            translateX={isExpanded?200:75}
                            iconComponent={
                                isExpanded
                                    ?<div className={`menu-box-bottom-item-${themeColor} menu-box-bottom-item menu-box-bottom-item-isExpanded`}>
                                        <IconCommon
                                            icon={`${themeColor===THEME_DEFAULT?"jiugongge":"jiugongge1"}`}
                                            className={"icon-s"}
                                        />
                                        <div>应用导航</div>
                                    </div>
                                    : <Tooltip placement="right" title={"应用导航"}>
                                        <div className={`menu-box-bottom-item-${themeColor} menu-box-bottom-item menu-box-bottom-item-not-isExpanded`}>
                                            <IconCommon
                                                icon={`${themeColor===THEME_DEFAULT?"jiugongge":"jiugongge1"}`}
                                                className={"icon-s"}
                                            />
                                        </div>
                                    </Tooltip>
                            }
                        />
                    }
                    {/* 用户头像及菜单 */}
                    {
                        (isFirst && FinalAvatarLink) && <FinalAvatarLink
                            changeTheme={changeTheme} // 主题切换函数
                            iconComponent={ // 头像部分的自定义渲染
                                <div className={` menu-box-bottom-item ${isExpanded?"":"menu-box-bottom-item-not-isExpanded"}`} >
                                    <Profile /> {/* 用户头像组件 */}
                                    {isExpanded && <div>{getUser()?.nickname}</div>} {/* 展开时显示昵称 */}
                                </div>
                            }
                            {...props}
                        />
                    }
                </div>
            </div>
            {/* 菜单展开/收起控制条 */}
            <div className={"menu-box-right-border"}>
                <div className={"menu-box-isexpanded"} onClick={()=>setIsExpanded(prev => !prev)}> {/* 点击切换展开状态 */}
                    {
                        isExpanded?<CaretLeftOutlined />:<CaretRightOutlined /> // 根据状态显示不同图标
                    }
                </div>
            </div>
        </div>
    );
};

export default LeftMenuCommon;